//
//  VC9CoreData.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/28.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit
import CoreData

class VC9CoreData: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let url = Bundle.main.url(forResource: "StudentModel", withExtension: ".momd") else {
            print("url is nil")
            return
        }
        // 数据库保存路径
        guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/student_model.sqlite") else {
            print("path is nil")
            return
        }
        let urlPath = URL(fileURLWithPath: path)
        // 数据模型
        guard let model = NSManagedObjectModel(contentsOf: url) else {
            print("model is nil")
            return
        }
        // 创建持久化存储协调者
        let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
        try! psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlPath, options: nil)
        // 创建数据管理上下文
        let ctx = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        ctx.persistentStoreCoordinator = psc
        
        // 创建数据对象
        let modelS = NSEntityDescription.insertNewObject(forEntityName: "SchoolClass", into: ctx) as! SchoolClass
        modelS.count = 10
        modelS.name = "学校"
        
        let modelT = NSEntityDescription.insertNewObject(forEntityName: "Student", into: ctx) as! Student
        modelT.name = "wanghz"
        modelT.number = "5"
        modelT.school = modelS
        
        // 进行存储
        if (try? ctx.save()) != nil {
            print("存储成功")
        }
        print("path=\(path)")
        
        
        // 创建一条查询请求
        let request = NSFetchRequest<SchoolClass>(entityName: "SchoolClass")
        // 设置查询条件
        request.predicate = NSPredicate(format: "count == %d", 10)
        // 进行查询
        guard let result = try? ctx.execute(request) as? NSAsynchronousFetchResult<SchoolClass> else {
            print("result is nil")
            return
        }
        print(result.finalResult?.first?.name ?? "NIL")
    }
}
